//
//  BranPage_Vm.swift
//  Pods
//
//  Created by eme on 2017/3/28.
//
//

import RxSwift
import NetWorkCore
import SwiftyJSON
import UtilCore

/*
 owner:cy
 update:2017年03月28日14:24:34
 info: 品牌详情界面vm
 */
class BranPage_Vm :Base_Vm {
    /// 表示正在刷新中
    let loading = ActivityIndicator()
    /*
     接收返回的数据
     */
    /// 返回首页数据
    let brandPageItem = PublishSubject<BrandPageModel>()
    ///添加收藏按钮
    let addusBrCollectionSubject = PublishSubject<(userid:String,brid:String)>()
    /// 删除商品
    let delusBrCollectionSubject = PublishSubject<String>()
    //如果是添加收藏则 返回cid 否则返回""
    let brCollectionSuccess =  PublishSubject<String>()
    /*
     通用设置
     */
    init(refreshTriger: Observable<String>) {
        super.init()
        let refreshSubject = Observable.of(
            refreshTriger,
            reloadTrigger.withLatestFrom(refreshTriger))
            .merge()
        refreshSubject
            .map{ BrandApi.brandRepertoryDetail(brid: $0) }
            .emeRequestApiForObj(BrandPageModel.self,activityIndicator: loading)
            .subscribe(onNext: { [unowned self] (result) in
                switch result {
                case .success(let data):
                    self.brandPageItem.onNext(data)
                case .failure(let error):
                    self.error.onNext(error)
                }
            })
            .disposed(by: disposeBag)
        addusBrCollectionSubject
            .map{ BrandApi.add(userid: $0.userid, brid: $0.brid)}
            .emeRequestApiForRegJson()
            .subscribe(onNext: {[unowned self] (result) in
                switch result {
                case .success(let data):
                    self.brCollectionSuccess.onNext(data.stringValue)
                case .failure(let error):
                    self.error.onNext(error)
                }
            }).disposed(by: disposeBag)
        delusBrCollectionSubject
            .map{ BrandApi.del(cid: $0)}
            .emeRequestApiForRegJson()
            .subscribe(onNext: {[unowned self] (result) in
                switch result {
                case .success( _):
                    self.brCollectionSuccess.onNext("")
                case .failure(let error):
                    self.error.onNext(error)
                }
            }).disposed(by: disposeBag)
    }
    
}

